package com.qc.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender javaMailSender;

    public String sendSimpleEmail(String to, String subject, String text) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("3468088075@qq.com"); // 发件人邮箱，可根据实际情况调整
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);

            javaMailSender.send(message);
            logger.info("邮件发送成功，收件人: {}, 主题: {}", to, subject);
            return "邮件发送成功";
        } catch (Exception e) {
            logger.error("邮件发送失败，收件人: {}, 主题: {}", to, subject, e);
            return "邮件发送失败";
        }
    }

    public String sendVerificationCodeEmail(String to) {
        String verificationCode = generateVerificationCode();
        String subject = "邮箱验证码";
        String text = "您的邮箱验证码是：" + verificationCode + "，请在规定时间内完成验证。";
        return sendSimpleEmail(to, subject, text);
    }

    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}